package com.qeng.aiwanba.net;

import android.os.Handler;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class URLLoader {
	private String data;
	private Handler uiHandler = new Handler();
	
	public URLLoader(final String path, final Listener listener){
		data = null;
		new Thread() {
			public void run() {
				Runnable getDataRunnable = new Runnable() {
					@Override
					public void run() {
						if(data != null){
							if(listener != null){
								listener.success(data);
							}
						}else{
							if(listener != null){
								listener.fail();
							}
						}
					}
				};
				
				try {
					URL url = new URL(path);
					HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
					// 设置连接超时时间
					urlConn.setRequestProperty("Connection", "Keep-Alive");
					urlConn.setRequestProperty("Accept-Charset", "utf-8");
//					urlConn.setRequestProperty("User-Agent", "checkversion");
					urlConn.setConnectTimeout(10 * 1000);
					// 开始连接
					urlConn.connect();
					// 判断请求是否成功
					if (urlConn.getResponseCode() == 200) {
						// 获取返回的数据
					    BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
			            String lines;
			            StringBuffer sbf = new StringBuffer();
			            while ((lines = reader.readLine()) != null) {
		                    lines = new String(lines.getBytes(), "utf-8");
		                    sbf.append(lines);
		                }
		                reader.close();
					    data = sbf.toString();
					} else {
						
					}
					uiHandler.post(getDataRunnable);
					// 关闭连接
					urlConn.disconnect();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
	}
	
	public interface Listener {
		public void success(String url);
		public void fail();
	}
}
